//
//  LogisticsCircleViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/18.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "LogisticsCircleViewController.h"
#import "CircleLogisticsTableViewCell.h"
#import "CircleLogisticsTopModel.h"
#import "CircleInfoModel.h"
#import "CircleContentModel.h"
#import "CircleCommentModel.h"
#import "CustomTapGestureRecognizer.h"
#import "SendLogisticsViewController.h"
#import "CommunityInputView.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface LogisticsCircleViewController ()<UITableViewDelegate, UITableViewDataSource, CircleLogisticsTableViewCellDelegate, KSPhotoBrowserDelegate, UIGestureRecognizerDelegate, UITextViewDelegate, UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
{
    CGFloat cellHeight;
    BOOL isReply;
    NSString *replyStr;
    NSInteger keyBoardHeight;
    NSNumber *duration;
    NSNumber *curve;
    CommunityInputView *_inputView;
    UIImageView *iconImageView;
    UIImageView *imageView;
    UILabel *nameLabel;
    NSMutableArray *photoArr;
    UIView *moreView;
    BOOL moreViewIsHidden;
    NSString *commentJoinId;
    NSString *tagId;
}
@property (nonatomic, strong) CircleInfoModel *infoDic;
@property (nonatomic, strong) UITableView *circleLogisticsTableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *circleDataArr;
@property (nonatomic, strong) NSArray *circleTopArr;
@end

@implementation LogisticsCircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    tagId = @"";
    isReply = NO;
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    self.page = 0;
    moreViewIsHidden = YES;
    photoArr = @[].mutableCopy;
    self.circleDataArr = @[].mutableCopy;
    [self setupUI];
    if (_circleType == ALLTYPE) {
        [self setupBottomView];
        [self requestLogisticsCircleTop];
    }
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_circleType == ALLTYPE) {
        [self requestLogisticsCircle];
        [self requestLogisticsCircleInfo];
    } else {
        [self requestOtherLogisticsCircle];
        [self requestOtherLogisticsCircleInfo];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_circleDataArr removeAllObjects];
    tagId = @"";
    isReply = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// MARK:获取系统键盘高度
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    keyBoardHeight = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    duration = [aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    curve = [aNotification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:duration.doubleValue];
        // 设置动画块中的动画属性变化的曲线
        [UIView setAnimationCurve:curve.integerValue];
        // 更改输入框位置
        _inputView.frame = CGRectMake(0, kScreenHeight - keyBoardHeight - _inputView.frame.size.height-STATUSBAR_HEIGHT-SCREER_HeiX-NAVIGATIONBAR_HEIGHT, kScreenWidth, _inputView.frame.size.height);
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:duration.doubleValue];
        // 设置动画块中的动画属性变化的曲线
        [UIView setAnimationCurve:curve.integerValue];
        // 更改输入框位置
        _inputView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, _inputView.frame.size.height);
    }];
}

- (void)setupUI {
    self.navigationController.navigationBar.translucent = NO;
    if (_circleType == ALLTYPE) {
        self.navigationItem.title = @"物流圈";
    } else {
        self.navigationItem.title = @"个人物流圈";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    _inputView = [[[NSBundle mainBundle] loadNibNamed:@"CommunityInputView" owner:self options:nil] firstObject];
    _inputView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 48);
    _inputView.inputTextView.delegate = self;
    [self.view addSubview:_inputView];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    singleTap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleTap];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap {
    [self hideKeyBoardAction];
}

- (void)setupScrollView {
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44*displaywidth)];
    CGFloat maxX = 0;
    for (int i = 0; i < _circleTopArr.count+1; i++) {
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(10*displaywidth*(i+1) + i*70*displaywidth, 10*displaywidth, 70*displaywidth, 24*displaywidth) ImageName:nil Target:self Action:@selector(closeSetUpAction:) Title:nil Font:14];
        if (i==0) {
            [btn setTitle:@"全部" forState:UIControlStateNormal];
        } else {
            CircleLogisticsTopModel *model = _circleTopArr[i-1];
            [btn setTitle:model.name forState:UIControlStateNormal];
        }
        btn.tag = 80 + i;
        btn.layer.cornerRadius = 5;
        btn.layer.masksToBounds = YES;
        if (i==0) {
            btn.backgroundColor = ThemeColor;
        } else {
            btn.backgroundColor = [UIColor lightGrayColor];
        }
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (i==_circleTopArr.count) {
            maxX = CGRectGetMaxX(btn.frame);
        }
        [scrollView addSubview:btn];
    }
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.contentSize = CGSizeMake(maxX + 10*displaywidth, 44*displaywidth);
    scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:scrollView];
}

- (void)setupCircleLogisticsTableView {
    if (_circleType == ALLTYPE) {
        self.circleLogisticsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT - 44*displaywidth - 50*displaywidth -STATUSBAR_HEIGHT-SCREER_HeiX-NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    } else {
        self.circleLogisticsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSBAR_HEIGHT-SCREER_HeiX-NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    }
    _circleLogisticsTableView.delegate = self;
    _circleLogisticsTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 310*displaywidth)];
//    headerView.userInteractionEnabled = YES;
    headerView.backgroundColor = [UIColor whiteColor];
    imageView = [ZCControl createImageViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 268*displaywidth) ImageName:nil];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [imageView addGestureRecognizer:tap];
//    imageView.userInteractionEnabled = YES;
    [headerView addSubview:imageView];
    iconImageView = [ZCControl createImageViewWithFrame:CGRectMake(0, 0, 84*displaywidth, 84*displaywidth) ImageName:nil];
    iconImageView.center = CGPointMake(SCREEN_WIDTH - 52*displaywidth, 268*displaywidth);
    UIButton *tapBtn = [ZCControl createButtonWithFrame:[headerView convertRect:iconImageView.frame toView:headerView] ImageName:nil Target:self Action:@selector(onClickIconImageView) Title:nil Font:10];
    tapBtn.backgroundColor = [UIColor clearColor];
    [imageView addSubview:iconImageView];
    [headerView addSubview:tapBtn];
    nameLabel = [ZCControl createLabelWithFrame:CGRectMake(0, 240*displaywidth, iconImageView.frame.origin.x-10*displaywidth, 25*displaywidth) Font:18 Text:@"" Color:UIColorHexValue(0xFFFFFF)];
    nameLabel.textAlignment = NSTextAlignmentRight;
    [imageView addSubview:nameLabel];
    _circleLogisticsTableView.tableHeaderView = headerView;
    _circleLogisticsTableView.tableFooterView = view;
    _circleLogisticsTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_circleLogisticsTableView];
    _circleLogisticsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    _circleLogisticsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    _circleLogisticsTableView.mj_footer.automaticallyHidden = YES;
    _circleLogisticsTableView.estimatedRowHeight = 0;
    _circleLogisticsTableView.estimatedSectionHeaderHeight = 0;
    _circleLogisticsTableView.estimatedSectionFooterHeight = 0;
    _circleLogisticsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)tapView:(UITapGestureRecognizer *)sender
{
    [self creatPhoto];
}

- (void)creatPhoto
{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    WEAKSELF;
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [weakSelf takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [weakSelf choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}


-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}


- (void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    WEAKSELF;
    [HttpTool uploadImageWithPath:@"/file/upload" params:nil thumbName:@"file" image:image success:^(id json) {
        if ([json server_Getcodecheck])
        {
            NSArray *imgAry = json[@"data"];
            if (imgAry.count > 0)
            {
                NSString *imgStr = imgAry[0];
                NSDictionary *dic = @{@"topicImg":imgStr};
                [weakSelf requestSaveUser:dic];
            }
        }
    } failure:^(NSError *error) {
        
    } progress:^(CGFloat progress) {
        
    }];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)requestSaveUser:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_userSave Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            UserAccountModel *model = [UserAccountModel shareMange];
            _userId = s_Integer(model.ID);
            [weakSelf requestOtherLogisticsCircleInfo];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:self.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)setupBottomView {
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50*displaywidth-STATUSBAR_HEIGHT-SCREER_HeiX-NAVIGATIONBAR_HEIGHT, SCREEN_WIDTH, SCREER_HeiX+50*displaywidth)];
    bottomView.backgroundColor = [UIColor whiteColor];
    UIButton *homeBtn = [ZCControl createButtonWithFrame:CGRectMake(5*displaywidth, 0, 60*displaywidth, 50*displaywidth) ImageName:@"sy_nav01" Target:self Action:@selector(onClickHomeBtn) Title:@"首页" Font:11];
    homeBtn.backgroundColor = [UIColor clearColor];
    [homeBtn setTitleColor:RGB(164, 164, 164) forState:UIControlStateNormal];
    [homeBtn setButtonContentCenter];
    [bottomView addSubview:homeBtn];
    UIButton *sendBtn = [ZCControl createButtonWithFrame:CGRectMake(70*displaywidth, 7.5*displaywidth, SCREEN_WIDTH-90*displaywidth, 35*displaywidth) ImageName:nil Target:self Action:@selector(onClickSendBtn) Title:@"我要发布..." Font:15];
    sendBtn.backgroundColor = RGB(221, 221, 221);
    [sendBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
    sendBtn.layer.cornerRadius = 4;
    sendBtn.layer.masksToBounds = YES;
    [bottomView addSubview:sendBtn];
    UILabel *lineLabel = [ZCControl createLabelWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5) Font:10 Text:nil Color:[UIColor lightGrayColor]];
    lineLabel.backgroundColor = UIColorHexValue(0xFFE7E7E7);
    [bottomView addSubview:lineLabel];
    [self.view addSubview:bottomView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _circleDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (cellHeight>0) {
        return cellHeight;
    } else {
        return 491;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CircleLogisticsTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"CircleLogisticsTableViewCell" owner:self options:nil].lastObject;
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.dataArr = self.circleDataArr;
    cellHeight = cell.cellHeight;
    if (indexPath.row == self.circleDataArr.count-1) {
        cell.lineLabel.hidden = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.moreCommentBtn.tag = indexPath.row;
    [cell.moreCommentBtn addTarget:self action:@selector(onClickMoreCommentBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.phoneBtn.tag = indexPath.row;
    [cell.phoneBtn addTarget:self action:@selector(onClickPhoneBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//MARK:点击方法
- (void)onClickIconImageView {
    LogisticsCircleViewController *circleVC = [[LogisticsCircleViewController alloc] init];
    circleVC.circleType = OTHERTYPE;
    circleVC.userId = _infoDic.ID;
    [self.navigationController pushViewController:circleVC animated:YES];
}

- (void)closeSetUpAction:(UIButton *)sender {
    for (int i = 0; i < _circleTopArr.count+1; i++) {
        UIButton *btn = [self.view viewWithTag:80 + i];
        if (i==sender.tag-80) {
            btn.backgroundColor = ThemeColor;
        } else {
            btn.backgroundColor = [UIColor lightGrayColor];
        }
    }
    if (sender.tag==80) {
        tagId = @"";
    } else {
        CircleLogisticsTopModel *model = _circleTopArr[sender.tag-80-1];
        tagId = model.ID;
    }
    [self requestLogisticsCircle];
}

- (void)onClickHomeBtn {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onClickSendBtn {
    UserAccountModel *userModel = [UserAccountModel shareMange];
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        [LTools showMBProgressWithText:@"请先登录" addToView:self.view];
        return;
    }
    if (userModel.isIdentify != 1)
    {
        [LTools showMBProgressWithText:@"请先实名认证" addToView:self.view];
        return;
    }
    SendLogisticsViewController *vc = [[SendLogisticsViewController alloc] init];
    vc.arr = _circleTopArr;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoMineVC:(NSInteger)num andCellIndex:(NSInteger)index {
    CircleContentModel *model = _circleDataArr[index];
    CircleCommentModel *commentModel = model.comments[num];
    commentJoinId = model.ID;
    isReply = YES;
    replyStr = [NSString stringWithFormat:@"回复 %@：", commentModel.commentUserName];
    _inputView.plaLabel.text = replyStr;
    [self.view insertSubview:_inputView aboveSubview:_circleLogisticsTableView];
    [_inputView.inputTextView becomeFirstResponder];
}

- (void)gotoCircleLogistics:(NSString *)targetId {
    LogisticsCircleViewController *circleVC = [[LogisticsCircleViewController alloc] init];
    circleVC.circleType = OTHERTYPE;
    circleVC.userId = targetId;
    [self.navigationController pushViewController:circleVC animated:YES];
}

- (void)onClickPhoneBtn:(UIButton *)sender {
    CircleContentModel *model = _circleDataArr[sender.tag];
    NSString *phoneStr = model.userPhone;
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneStr]]];
}

- (void)onClickMoreCommentBtn:(UIButton *)sender {
    CircleContentModel *model = _circleDataArr[sender.tag];
    commentJoinId = model.ID;
    isReply = NO;
    [self.view insertSubview:_inputView aboveSubview:_circleLogisticsTableView];
    [_inputView.inputTextView becomeFirstResponder];
}

- (void)onClickCommentBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    CircleLogisticsTableViewCell *cell = [_circleLogisticsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
    cell.moreView.hidden = !sender.selected;
    cell.moreView.frame = CGRectMake(cell.commentBtn.frame.origin.x-200, cell.commentBtn.center.y-20.5, 200, 41);
}

// MARK: UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        _inputView.plaLabel.hidden = YES;
    } else {
        _inputView.plaLabel.hidden = NO;
    }
    // 计算textView文本高度
    CGRect textViewHeight = [Utilities calculateWidthAndHeightWithWidth:kScreenWidth - 20 height:1000 text:textView.text font:[UIFont systemFontOfSize:13]];
    CGFloat aHeight = textViewHeight.size.height - 31 > 0 ? textViewHeight.size.height - 31 : 0;
    
    _inputView.frame = CGRectMake(0, kScreenHeight - keyBoardHeight - aHeight - 48-STATUSBAR_HEIGHT-SCREER_HeiX-NAVIGATIONBAR_HEIGHT, kScreenWidth, 48 + aHeight);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        if (textView.text.length == 0) {
//            [MBProgressHUD showTip:@"说点什么吧" toView:self.view];
            [LTools showMBProgressWithText:@"说点什么吧" addToView:self.view];
        } else {
            // 调用接口发送评论
            //            NSString *string = [textView.text stringByReplacingOccurrencesOfString: @" " withString: @""];
            [self sendCommentWithText:textView.text];
        }
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
    if (str.length > 256)
    {
        textView.text = [str substringToIndex:256];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入的字符数不能超过256" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }else{
        NSLog(@"%lu",(unsigned long)textView.text.length);
    }
    return YES;
}

// MARK: 隐藏键盘
- (void)hideKeyBoardAction
{
    [_inputView.inputTextView resignFirstResponder];
}

- (void)sendCommentWithText:(NSString *)text {
    WEAKSELF;
    NSString *str = text;
    if (isReply) {
        str = [NSString stringWithFormat:@"%@%@", replyStr, text];
    }
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsComment Parmers:@{@"type":@"2", @"content":str, @"joinId":commentJoinId} Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             _inputView.inputTextView.text = @"";
             [self hideKeyBoardAction];
             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf requestLogisticsCircle];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

// MARK: - KSPhotoBrowserDelegate
- (void)ks_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index {
    NSLog(@"selected index: %ld", index);
}

- (void)showImageWithIndexPath:(NSInteger)index imageIndex:(NSInteger)imageIndex
{
    [photoArr removeAllObjects];
    CircleContentModel *model = self.circleDataArr[index];
    NSString *str1=model.imgs;
    NSArray *temp;
    if (str1 && ![str1 isEqual:@""]) {
        if ([str1 containsString:@","]) {
            temp=[str1 componentsSeparatedByString:@","];
        } else {
            temp=@[str1];
        }
    }
    for (int i = 0; i < temp.count; i++) {
        CircleLogisticsTableViewCell *cell = (CircleLogisticsTableViewCell *)[_circleLogisticsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        UIImageView *imageView = [cell.pictureBackgroundView viewWithTag:i+100];
        KSPhotoItem *item = [KSPhotoItem itemWithSourceView:imageView imageUrl:[NSURL URLWithString:temp[i]]];
        [photoArr addObject:item];
    }
    KSPhotoBrowser *ksBrowser = [KSPhotoBrowser browserWithPhotoItems:photoArr selectedIndex:imageIndex];
    [KSPhotoBrowser setImageManagerClass:KSYYImageManager.class];
    ksBrowser.delegate = self;
    ksBrowser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
    ksBrowser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlurPhoto;
    ksBrowser.loadingStyle = KSPhotoBrowserImageLoadingStyleIndeterminate;
    ksBrowser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleText;
    ksBrowser.bounces = NO;
    [ksBrowser showFromViewController:self];
}

- (void)loadNewHeaderData
{
    _page = 0;
    if (_circleType == ALLTYPE) {
        [self requestLogisticsCircle];
    } else {
        [self requestOtherLogisticsCircle];
    }
    
}

- (void)loadMoreFootData
{
    _page ++;
    if (_circleType == ALLTYPE) {
        [self requestLogisticsCircle];
    } else {
        [self requestOtherLogisticsCircle];
    }
    
}

// MARK:加载数据方法
- (void)requestOtherLogisticsCircle {
    WEAKSELF;
    NSDictionary *dic = @{@"page":s_Integer(_page),@"size":@"10", @"user.id":_userId};
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsCellInfo Parmers:dic Success:^(id obj)
     {
         [weakSelf.circleLogisticsTableView.mj_header endRefreshing];
         [weakSelf.circleLogisticsTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSArray *dataArray = [CircleContentModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (weakSelf.page == 0)
                 {
                     [weakSelf.circleDataArr removeAllObjects];
                 }
                 [weakSelf.circleDataArr addObjectsFromArray:dataArray];
                 if (!_circleLogisticsTableView) {
                     [self setupCircleLogisticsTableView];
                 }
                 [weakSelf.circleLogisticsTableView reloadData];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [weakSelf.circleLogisticsTableView.mj_header endRefreshing];
         [weakSelf.circleLogisticsTableView.mj_footer endRefreshing];
     }];
}

- (void)requestOtherLogisticsCircleInfo {
    WEAKSELF;
    NSDictionary *dic = @{@"id":_userId};
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsSelect Parmers:dic Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.infoDic = [CircleInfoModel mj_objectWithKeyValues:obj[@"data"]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (!_circleLogisticsTableView) {
                     [self setupCircleLogisticsTableView];
                 }
                 NSURL *imageViewUrl = [NSURL URLWithString:weakSelf.infoDic.topicImg];
                 [imageView sd_setImageWithURL:imageViewUrl placeholderImage:nil];
                 NSURL *iconImageViewUrl = [NSURL URLWithString:weakSelf.infoDic.headImg];
                 [iconImageView sd_setImageWithURL:iconImageViewUrl placeholderImage:nil];
                 nameLabel.text = weakSelf.infoDic.username;
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

// MARK:加载数据方法
- (void)requestLogisticsCircle {
    WEAKSELF;
    NSDictionary *dic;
    if (tagId && ![tagId isEqual:@""]) {
        dic = @{@"page":s_Integer(_page),@"size":@"10", @"tagId":tagId};
    } else {
        dic = @{@"page":s_Integer(_page),@"size":@"10"};
    }
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsCellInfo Parmers:dic Success:^(id obj)
     {
         [weakSelf.circleLogisticsTableView.mj_header endRefreshing];
         [weakSelf.circleLogisticsTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSArray *dataArray = [CircleContentModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (weakSelf.page == 0)
                 {
                     [weakSelf.circleDataArr removeAllObjects];
                 }
                 [weakSelf.circleDataArr addObjectsFromArray:dataArray];
                 if (!_circleLogisticsTableView) {
                     [self setupCircleLogisticsTableView];
                 }
                 [weakSelf.circleLogisticsTableView reloadData];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [weakSelf.circleLogisticsTableView.mj_header endRefreshing];
         [weakSelf.circleLogisticsTableView.mj_footer endRefreshing];
     }];
}

- (void)requestLogisticsCircleInfo {
    WEAKSELF;
    NSDictionary *dic = @{};
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsTopInfo Parmers:dic Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.infoDic = [CircleInfoModel mj_objectWithKeyValues:obj[@"data"]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (!_circleLogisticsTableView) {
                     [self setupCircleLogisticsTableView];
                 }
                 NSURL *imageViewUrl = [NSURL URLWithString:weakSelf.infoDic.topicImg];
                 [imageView sd_setImageWithURL:imageViewUrl placeholderImage:nil];
                 NSURL *iconImageViewUrl = [NSURL URLWithString:weakSelf.infoDic.headImg];
                 [iconImageView sd_setImageWithURL:iconImageViewUrl placeholderImage:nil];
                 nameLabel.text = weakSelf.infoDic.username;
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

- (void)requestLogisticsCircleTop {
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_CircleLogisticsTop Parmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.circleTopArr = [CircleLogisticsTopModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf setupScrollView];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
